<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\Tools\BookCommentStatus;
use App\Models\Book;
use App\Models\BookComment;
use App\Models\Category;
use App\Models\User;
use Carbon\Carbon;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Show;
use DB;

class UserBookCommentsController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('用户评论列表');
            //$content->description('description');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($book_id,$id)
    {
        return Admin::content(function (Content $content) use ($id,$book_id) {

            $content->header('修改评论');
            //$content->description('description');

            $content->body($this->form()->edit($id));
        });
    }

    public function update($book_id, $id)
    {
        return $this->form()->update($id);
    }

    public function destroy($book_id,$id)
    {
        //$this->form()->destroy()
        BookComment::query()->where('book_id',$book_id)->where('id',$id)->update(['deleted'=>1]);
        return ['status'=>true,'message'=>'删除成功'];
    }

    public function show($id, Content $content)
    {
        return $content
            ->header('评论详情')
            //->description('description')
            ->body($this->detail($id));
    }

    public function detail($id)
    {
        $show = new Show(Book::findOrFail($id));

        $show->panel()
            ->tools(function ($tools) {
                $tools->disableEdit();
                //$tools->disableList();
                $tools->disableDelete();
            });

        $show->image('图片封面')->image(config('app.qiniu_image_domain').'/');
        $show->title('图片名称');
        $show->field('user_book_comments','用户评论总数')->as(function () use ($id){
            return BookComment::query()->where('book_id',$id)->where('type',1)->where('deleted',0)->count();
        });

        $show->divider();
        $show->comments('用户评论列表', function ($comments) {
            $comments->model()->where('type', '=', 1)->where('deleted',0);

            $comments->user()->wechat_avatar('用户头像')->image(config('app.qiniu_image_domain'),50,50);
            $comments->user()->wechat_nickname('用户昵称');
            $comments->content('评价内容')->style('width:650px');
            //$comments->rate('评分');
            $comments->rate('评分')->display(function ($rate) {
                $html = "<i class='fa fa-star' style='color:#ff8913'></i>";

                return join('&nbsp;', array_fill(0, min(5, $rate), $html));
            });

            $comments->status('审核状态')->display(function ($status){
                $str = '';
                switch ($status)
                {
                    case 1:
                        $str = '待审核';
                        break;
                    case 2:
                        $str = '已审核';
                        break;
                    case 3:
                        $str = '审核未过';
                        break;
                }
                return $str;
            });

            $comments->disableCreateButton();
            $comments->disableExport();
            $comments->disableRowSelector();
            //$comments->disableActions();
            $comments->disableFilter();

            $comments->actions(function ($actions) {
                $actions->disableDelete();
                //$actions->disableEdit();
                $actions->disableView();
            });
        });

        return $show;
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Book::class, function (Grid $grid) {
            $grid->model()->where('deleted',0)->where('on_sale',1);
            $grid->image('图书封面')->image(config('app.qiniu_image_domain'), 50, 50);
            $grid->column('title', '图书名称');

            $grid->column('book_comments_num','用户评论数')->display(function () {
                return BookComment::query()->where('book_id',$this->id)->where('type',1)->where('deleted',0)->count();
            });

            /*$grid->column('book_comments_num1','待审核')->display(function () {
                return BookComment::query()->where('book_id',$this->id)->where('type',1)->where('deleted',0)->where('status',1)->count();
            });*/
            $grid->column('uncheck_comment_num', '待审核')->sortable();

            $grid->column('book_comments_num2','审核通过')->display(function () {
                return BookComment::query()->where('book_id',$this->id)->where('type',1)->where('deleted',0)->where('status',2)->count();
            });
            $grid->column('book_comments_num3','审核未过')->display(function () {
                return BookComment::query()->where('book_id',$this->id)->where('type',1)->where('deleted',0)->where('status',3)->count();
            });

            $grid->category_parent_id('一级分类')->display(function($value) {
                $category = Category::query()->where('id',$value)->first();
                if(!empty($category))
                {
                    return $category->title;
                }
                return '';
            });
            $grid->category_id('二级分类')->display(function($value) {
                $category = Category::query()->where('id',$value)->first();
                if(!empty($category))
                {
                    return $category->title;
                }
                return '';
            });

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->like('title', '商品名称');
                $filter->equal('category_parent_id', '一级分类')
                    ->select(Category::getSelectOptions())
                    ->load('category_id', '/api/admin/second/categories');

                $filter->equal('category_id', '二级分类')->select();
                //$filter->equal('status','审核状态')->select(['1' => '待审核','2'=>'审核通过','3'=>'审核未过']);
            });
            /*$grid->model()->where('deleted',0)->where('type',1);
            $grid->model()->status(Request::get('status'));
            $grid->user()->wechat_nickname('用户昵称');
            $grid->book()->title('图书名称');

            $grid->rate('评分')->display(function ($rate) {
                $html = "<i class='fa fa-star' style='color:#ff8913'></i>";

                return join('&nbsp;', array_fill(0, min(5, $rate), $html));
            });
            $grid->good_num('点赞数');
            $grid->status('审核状态')->display(function ($status){
                $str = '';
                switch ($status)
                {
                    case 1:
                        $str = '待审核';
                        break;
                    case 2:
                        $str = '已审核';
                        break;
                    case 3:
                        $str = '审核未过';
                        break;
                }
                return $str;
            });
            $grid->created_at('创建时间');*/
            //$grid->updated_at();
            /*$grid->tools(function ($tools) {
                $tools->append(new BookCommentStatus());
            });*/

            $grid->actions(function ($actions) {
                //$actions->disableView();
                $actions->disableDelete();
                $actions->disableEdit();
            });

            $grid->disableRowSelector();
            $grid->disableExport();
            $grid->disableCreateButton();
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(BookComment::class, function (Form $form) {
            $form->display('id', 'ID');
            //$form->display('user.wechat_nickname','用户昵称');
            $form->text('user.wechat_nickname','用户昵称')->attribute('disabled', 'true');
            //$form->select('user_id','所选用户')->options(User::getSelectOptions())->rules('required');
            //$form->number('rate', '评分')->max(5)->min(1)->default(5)->attribute('disabled', 'true');
            $form->text('rate', '评分')->attribute('disabled', 'true');
            $form->textarea('content','评价内容')->rows(5)->attribute('disabled', 'true');
            $form->radio('status','审核状态')->options(['1' => '待审核', '2'=> '审核通过', '3'=>'审核未过']);

            $form->tools(function (Form\Tools $tools) {
                $tools->disableView();
                $tools->disableDelete();
            });

            //$form->hidden('type')->value(2);
            //$form->hidden('status')->value(2);
            $form->saved(function (Form $form) {
                $user_id = $form->model()->user_id;
                $status = $form->model()->status;
                $book_id = $form->model()->book_id;

                if($status == 3)
                {
                    Book::query()->where('id',$book_id)->decrement('uncheck_comment_num');
                }

                if($status == 2)
                {
                    Book::query()->where('id',$book_id)->decrement('uncheck_comment_num');

                    $result = BookComment::query()
                        ->where('book_id', $book_id)
                        ->first([
                            DB::raw('count(*) as review_count'),
                            DB::raw('avg(rate) as rating')
                        ]);
                    // 更新商品的评分和评价数
                    Book::query()->where('id',$book_id)->update([
                        'review_count' => $result->review_count,
                        'rating' => $result->rating,
                    ]);

                    DB::table('user_vip_time_records')->insert([
                        'user_id' => $user_id,
                        'type' => 2,
                        'days' => 2,
                        'created_at' => Carbon::now(),
                        'intro' => '优质书评'
                    ]);

                    $user = User::query()->where('id',$user_id)->first();
                    if($user->is_vip == 1)
                    {
                        if(!empty($user->vip_start_time) && !empty($user->vip_end_time))
                        {
                            $new_end_time = strtotime("+2 days",$user->vip_end_time);
                            $user->update([
                                'vip_end_time' => $new_end_time
                            ]);
                        }
                    }
                    else
                    {
                        $vip_start_time = time();
                        $vip_end_time = strtotime("+2 days",$vip_start_time);
                        $user->update([
                            'is_vip' => 1,
                            'vip_end_time' => $vip_end_time,
                            'vip_start_time' => $vip_start_time
                        ]);
                    }

                    //发送短信
                    $sms = app('easysms');
                    try {
                        $sms->send($user->telephone,[
                            'template' => 'SMS_146807423',
                            'data' => [
                                'name' => $user->wechat_nickname
                            ],
                        ]);
                    } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
                        $message = $exception->getException('aliyun')->getMessage();
                        dd($message);
                    }
                }
            });
        });
    }
}
